<script setup>
import * as ww from '@wecom/jssdk'
import login from "@/api/login.js";
import {useTagStore, useUserStore} from "@/store/index.js";
import {inject, onMounted, ref} from "vue";
import user from "@/api/system/user.js";
import {useRoute, useRouter} from "vue-router";
import {Message} from "@arco-design/web-vue";

const route = useRoute()
const env = import.meta.env
const loading = defineModel();
const userStore = useUserStore()
const router = useRouter()
const props = defineProps({
  type: {
    type: String,
    default: ''
  }
})
const redirect = inject('redirect')
const emit = defineEmits(['close'])
let wxLogin
const handleSubmit = async (code) => {
  if (loading.value) {
    return
  }
  loading.value = true
  if (props.type != 'bind') {
    userStore.wwLogin(code).then(result => {
      if (!result) {
        wxLogin.unmount()
        wwInit()
        loading.value = false
        return
      }
      useTagStore().clearTags()
      wxLogin.unmount()
      router.push(redirect)
      loading.value = false
    })
  } else {
    user.bindSocialite('wework', code).then(result => {
      if (!result) {
        wxLogin.unmount()
        wwInit()
      } else if (!result.success) {
        Message.error(result.message)
      } else {
        Message.success('绑定成功')
      }
      emit('close')
      loading.value = false
    })
  }
}

const isWeChat = function (){
  const ua = window.navigator.userAgent.toLowerCase();
  return ua.match(/microMessenger/i) == 'micromessenger';
}

const weworkOath = ()=>{
  if(!route.query.code){
    login.getWxConfig().then(res=>{
      window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + res.data.appid + '&redirect_uri=' + encodeURIComponent(location.href) + '&response_type=code&scope=snsapi_base&state=STATE&agentid=' + res.data.agentid + '#wechat_redirect'
    })
    return;
  }
  userStore.wwLogin(route.query.code).then(result => {
    if (!result) {
      return
    }
    useTagStore().clearTags()
    router.push(redirect)
  })
}

const wwInit = () => {
  if(isWeChat()){
    weworkOath()
    return;
  }
  login.getWxConfig().then(res => {
    wxLogin = ww.createWWLoginPanel({
      el: '#ww_login',
      params: {
        login_type: 'CorpApp',
        appid: res.data.appid,
        agentid: res.data.agentid,
        redirect_uri: res.data.redirect_uri,
        state: 'loginState',
        redirect_type: 'callback',
        panel_size: 'small',
      },
      onLoginSuccess({code}) {
        handleSubmit(code)
      },
    })
  }).finally(() => {
    loading.value = false
  })
}
onMounted(() => {
  console.log('wx onMounted')
  wwInit()
})
</script>

<template>
  <a-spin :loading="loading" style="width: 400px;height: 300px;" class="text-center flex justify-center items-center"
          tip="加载数据中...">
    <div id="ww_login" style="margin-top: -104px;" class="flex justify-center"></div>
  </a-spin>
</template>

<style>
</style>